/**
 *
 */
package com.dhcc.android.base.utils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.Toast;

import com.dhcc.android.base.R;
import com.dhcc.android.base.common.adapter.ImageGridAdapter;
import com.dhcc.android.base.common.bean.BasicProperties;
import com.dhcc.android.base.common.bean.File;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.view.DateTimePickerView;
import com.dhcc.android.base.common.view.FlowLayout;
import com.dhcc.android.base.common.view.GetLocationByMapPoup;
import com.dhcc.android.base.common.view.MyActorPopWindow;
import com.dhcc.android.base.common.view.MyGridView;
import com.dhcc.android.base.gis.FactoryGPS;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import srs.Geometry.FormatConvert;
import srs.Geometry.IGeometry;
import srs.Geometry.IPolygon;

/**
 * 动态表单控件工具
 *
 * @author pengling
 * @date 2015-5-29
 */
public class FormUtil {
    boolean isArea = false;
    public static String text = "";
    public static String text_pho = "";
    private static Activity activity;
    private static BasicProperties field;
    private boolean isEnd;
    public static boolean isphotoDelete = false;
    private static List<BasicProperties> fieldList;
    /**
     * 照片信息集合
     */
    public static Map<String, String> photoMap = null;
    /***/
    public static List<String> photoList = null;
    public static List<String> photoKeyList = null;

    public FormUtil(Activity activity, BasicProperties field, boolean isEnd,
                    List<BasicProperties> fieldList) {
        this.activity = activity;
        this.field = field;
        this.isEnd = isEnd;
        this.fieldList = fieldList;
    }

    public static String fieldSet = "";

    public View initEditText(int inputType, int imeOptions, String title,
                             Map<String, String> dataMap) {
        View childView = (View) activity.getLayoutInflater().inflate(
                R.layout.util_form_edittext, null);
        TextView title_text = (TextView) childView
                .findViewById(R.id.title_text);
        if (StringUtil.isEmpty(title)) {
            title = field.getLabel();
        }
        title_text.setText(title);
        doSetView(childView);
        final ClearEditText edit_content = (ClearEditText) childView
                .findViewById(R.id.edit_content);
        edit_content.setInputType(inputType);
        if (inputType == 00) {// 非00
            edit_content.setFocusable(false);
            edit_content.setEnabled(false);
        }
        System.out.println("dataMap:" + dataMap);
        if (dataMap != null) {// 获得老值
            String value = dataMap.get(field.getName());
            edit_content.setText(value);
            if (StringUtil.isNotEmpty(value)) {
                edit_content.setSelection(value.length());
            }
            if (field.isShow() && !field.isEditable()) {// 显示但不可编辑
                edit_content.setEnabled(false);
                edit_content.setFocusable(false);
            }
        }

        initButtonView(childView, edit_content);// 增加小按钮

        edit_content.addTextChangedListener(new ValueWatcher(edit_content,
                field.getName(), field.getInput()));
        return childView;
    }

    /**
     * 初始化选择框
     *
     * @param isSingle
     * @param list
     * @return
     */
    public View initSelectPoup(final boolean isSingle,
                               final List<KeyValueBean> list, String title,
                               Map<String, String> dataMap, String beanType) {
        View childView = (View) activity.getLayoutInflater().inflate(
                R.layout.util_form_select, null);
        final TextView text_id = (TextView) childView
                .findViewById(R.id.text_id);
        final EditText edit_content = (EditText) childView
                .findViewById(R.id.edit_content);
        final TextView text_content = (TextView) childView
                .findViewById(R.id.text_content);
        TextView title_text = (TextView) childView
                .findViewById(R.id.title_text);
        if (StringUtil.isNotEmpty(title)) {
            title_text.setText(title);
        } else {
            title_text.setText(field.getLabel());
        }
        int textType = getTextType(field.getInput());
        System.out.println("textType:" + textType);
        if (textType != 00) {// 可编辑
            edit_content.setVisibility(View.VISIBLE);
            text_content.setVisibility(View.GONE);
            edit_content.setInputType(textType);
            edit_content.setEnabled(true);
            edit_content.setFocusableInTouchMode(true);
            edit_content.setFocusable(true);
            edit_content.requestFocus();
            initSelectView(edit_content, dataMap, list, textType, isSingle,
                    text_id, true, beanType);
        } else {
            edit_content.setVisibility(View.GONE);
            text_content.setVisibility(View.VISIBLE);
            text_content.setFocusableInTouchMode(true);
            text_content.setFocusable(true);
            text_content.requestFocus();
            text_content.setEnabled(true);
            initSelectView(text_content, dataMap, list, textType, isSingle,
                    text_id, false, beanType);
        }

        doSetView(childView);
        // doBothView(childView, title_text);

        // String value = edit_content.getText().toString();
        // if (textType != 00 && StringUtil.isNotEmpty(value)) {
        // edit_content.setSelection(value.length());
        // }
        initButtonView(childView, edit_content);
        return childView;
    }

    private void initSelectView(final TextView edit_content,
                                Map<String, String> dataMap, final List<KeyValueBean> list,
                                int textType, final boolean isSingle, final TextView text_id,
                                final boolean isEdit, final String beanType) {
        if (dataMap != null) {// 获得老值
            String value = dataMap.get(field.getName());
            String newValue = "", newId = "";
            if (list != null && list.size() > 0 && StringUtil.isNotEmpty(value)) {
                for (KeyValueBean keyValueBean : list) {
                    String key = keyValueBean.getKey();
                    String selectValue = keyValueBean.getValue();
                    if (value.contains(",")) {// 多个
                        String val[] = value.split(",");// value=112,333
                        for (String str : val) {// str=112
                            if (key.equals(str)) {
                                if (StringUtil.isEmpty(newValue)) {
                                    newValue = selectValue;
                                } else {
                                    newValue = newValue + "," + selectValue;
                                }
                            }
                            if (StringUtil.isNotEmpty(selectValue)
                                    && str.contains(selectValue)) {// str=春小麦(117)
                                // selectValue=春小麦
                                if (StringUtil.isEmpty(newId)) {
                                    newId = key;
                                } else {
                                    newId = newId + "," + key;
                                }
                            }
                        }
                    } else {// 只有一个
                        if (key.equals(value)) {
                            newValue = selectValue;
                        }
                        if (value.contains(selectValue)) {// str=春小麦(117)
                            // selectValue=春小麦
                            if (StringUtil.isEmpty(newId)) {
                                newId = key;
                            }
                        }
                    }

                }
            }
            if (StringUtil.isEmpty(newValue)) {
                newValue = value;
            }
            if (StringUtil.isEmpty(newId)) {
                newId = value;
            }
            System.out.println("newId:" + newId);
            edit_content.setText(newValue);
            text_id.setText(newId);
            if (field.isShow() && !field.isEditable()) {// 显示但不可编辑
                edit_content.setEnabled(false);
                edit_content.setFocusable(false);
            }
        }
        edit_content.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    boolean touchable = event.getX() > (edit_content.getWidth() - edit_content
                            .getTotalPaddingRight())
                            && (event.getX() < ((edit_content.getWidth() - edit_content
                            .getPaddingRight())));

                    if (touchable || !isEdit) {
                        System.out.println("点击添加了");
                        // 判断隐藏软键盘是否弹出
                        if (activity.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                            // 隐藏软键盘
                            activity.getWindow()
                                    .setSoftInputMode(
                                            WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                        }
                        MyActorPopWindow myActorWindow = new MyActorPopWindow(
                                activity, v, isSingle);
                        myActorWindow.showActorPanel(text_id, edit_content,
                                list, beanType);
                    }
                }
                return false;
            }
        });
        // if (isSaveKey) {// 是否保存key值
        // edit_content.addTextChangedListener(new ValueWatcher(text_id, field
        // .getName(), field.getInput()));
        // } else {
        edit_content.addTextChangedListener(new ValueWatcher(edit_content,
                field.getName(), field.getInput()));
        // }
    }

    /**
     * 初始化按钮
     *
     * @param childView
     * @param edit_content
     */
    public void initButtonView(View childView, final TextView edit_content) {
        FlowLayout button_layout = (FlowLayout) childView
                .findViewById(R.id.button_layout);
        field.setButtonlabel(initBtnLabel(field));// 加上"3"和"4"开头的按钮样式

        if (StringUtil.isNotEmpty(field.getButtonlabel())
                && (field.isShow() && field.isEditable())) {
            button_layout.setVisibility(View.VISIBLE);
            String buttonLabel = field.getButtonlabel();
            System.out.println("按钮数：" + buttonLabel);
            if (field.getLabel().endsWith("（亩）")) {
                isArea = true;
            }
            String[] buttonStrs = buttonLabel.split(",");
            for (int i = 0; i < buttonStrs.length; i++) {
                final Button btn = (Button) activity.getLayoutInflater()
                        .inflate(R.layout.util_form_button, null);
                btn.setText(buttonStrs[i]);
                btn.setId(i);
                button_layout.addView(btn);
                // 动态按钮点击
                btn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StringUtil.isFastDoubleClick(500)) {
                            return;
                        }
                        String text = btn.getText().toString();
                        if (text.equals("图上选点")) {
                            // 弹出图上选点的弹框,里面放置一个map，
                            GetLocationByMapPoup poup = new GetLocationByMapPoup(
                                    activity);
                            poup.initPopWindow(v, edit_content, text);
                        } else if (text.equals("几何计算")) {
                            IGeometry geometry = null;
//							if (!((DemandMainActivity) activity).oldDataMap
//									.isEmpty()
//									&& StringUtil
//											.isNotEmpty(((DemandMainActivity) activity).oldDataMap
//													.get("GEO"))) {
//								String geo = ((DemandMainActivity) activity).oldDataMap
//										.get("GEO");
//								try {
//									geometry = FormatConvert.WKTToPolygon(geo);
//								} catch (IOException e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								}
//							} else if (Constants.geometrys != null) {
//								geometry = Constants.geometrys.get(0);
//							}
//							if (geometry != null) {
//								/* 计算面积 */
//								double area = ((IPolygon) geometry).Area();
//								/* 周长 */
//								double longth = ((IPolygon) geometry).Length();
//								/* 中心点位置 */
//								// IPoint centerPoint = (IPoint) geometry
//								// .CenterPoint();
//								// double[] centerXY = GPSConvert.PROJECT2GEO(
//								// centerPoint.x, centerPoint.y, CommenUtil
//								// .getMap().getGeoProjectType());
//								// System.out.println("centerXY:"+centerXY);
//								System.out.println("area:" + area);
//								if (isArea && area >= 99) {
//									area = area / 666.7;
//								}
//
//								DecimalFormat df = new DecimalFormat(
//										"######0.00");
//								edit_content.setText(df.format(area) + "");// 几何计算出结果显示
//							}
//							System.out.println("得到的:" + geometry);

                        } else if (text.contains("GPS")) {
                            isFirst = true;
                            // CommenUtil.startGPSService(activity,
                            // new GetGPSBroadcastReceiver(edit_content));//
                            // 开启GPS
                            edit_content.setText(FactoryGPS.conGPSInfo);
                        } else if (text.contains("-") || text.contains("+")
                                || text.contains("*") || text.contains("/")) {// 加减乘除
                            String text_array[] = null;

                            if (text.contains("-")) {
                                text_array = text.split("-");
                            } else if (text.contains("+")) {
                                text_array = text.split("+");
                            } else if (text.contains("*")) {
                                text_array = text.split("*");
                            } else if (text.contains("/")) {
                                text_array = text.split("/");
                            }
                            // String text0 = "0", text1 = "0";
                            String text_arrayInt[] = new String[text_array.length];
                            if (text_array.length > 1) {
                                for (BasicProperties bp : fieldList) {
                                    /*
									 * if (bp.getLabel().equals(text_array[0]))
									 * { text_arrayInt[0] =
									 * ((DemandMainActivity) activity).addMap
									 * .get(bp.getName()); } else if
									 * (bp.getLabel().equals( text_array[1])) {
									 * text_arrayInt[1] = ((DemandMainActivity)
									 * activity).addMap .get(bp.getName()); }
									 */
                                    for (int j = 0; j < text_array.length; j++) {
                                        if (bp.getLabel().equals(text_array[j])) {
//											text_arrayInt[j] = ((DemandMainActivity) activity).addMap
//													.get(bp.getName());
                                        }
                                    }
                                }
                            }
							/*System.out.println("第一名称：" + text_array[0]
									+ ",第二名称：" + text_array[1] + ",第三名称："
									+ text_array[2]);
							System.out.println("第一数值:" + text_arrayInt[0]
									+ ",第二数值：" + text_arrayInt[1] + ",第三数值："
									+ text_arrayInt[2]);*/
                            Double result = 0.0;
                            for (int j = 0; j < text_arrayInt.length; j++) {
                                text_arrayInt[j] = (text_arrayInt[j] == null) ? "0.0"
                                        : text_arrayInt[j];
                                text_arrayInt[j] = (text_arrayInt[j].trim()
                                        .equalsIgnoreCase("")) ? "0.0"
                                        : text_arrayInt[j];
                            }
							/*
							 * text_arrayInt[1] = (text_arrayInt[1] == null) ?
							 * "0.0" : text_arrayInt[1]; text_arrayInt[1] =
							 * (text_arrayInt[1].trim().equalsIgnoreCase("")) ?
							 * "0.0" : text_arrayInt[1]; text_arrayInt[0] =
							 * (text_arrayInt[0] != null) ? text_arrayInt[0] :
							 * "0.0"; text_arrayInt[0] =
							 * (!text_arrayInt[0].trim().equalsIgnoreCase("")) ?
							 * text_arrayInt[0] : "0.0";
							 */
                            if (text.contains("-")) {
                                for (int j = 0; j < text_arrayInt.length; j++) {
                                    if (Double
                                            .parseDouble(text_arrayInt[j]) < 0) {
                                        result = 0.0;
                                        Toast.makeText(btn.getContext(),
                                                "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                                .show();
                                        break;
                                    } else {
                                        if (j == 0) {
                                            result = Double
                                                    .parseDouble(text_arrayInt[j])
                                                    - Double.parseDouble(text_arrayInt[j + 1]);
                                        } else if (j < text_arrayInt.length - 1) {
                                            result = result
                                                    - Double.parseDouble(text_arrayInt[j + 1]);
                                        }
                                    }

                                }

                                if (result < 0) {
                                    result = 0.0;
                                    Toast.makeText(btn.getContext(),
                                            "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                            .show();
                                }
                            } else if (text.contains("+")) {
                                for (int j = 0; j < text_arrayInt.length; j++) {
                                    if (Double
                                            .parseDouble(text_arrayInt[j]) < 0) {
                                        Toast.makeText(btn.getContext(),
                                                "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                                .show();
                                        result = 0.0;
                                        break;
                                    } else {
                                        if (j == 0) {
                                            result = Double
                                                    .parseDouble(text_arrayInt[j])
                                                    + Double.parseDouble(text_arrayInt[j + 1]);
                                        } else if (j < text_arrayInt.length - 1) {
                                            result = result
                                                    + Double.parseDouble(text_arrayInt[j + 1]);
                                        }
                                    }

                                }

                                if (result < 0) {
                                    result = 0.0;
                                    Toast.makeText(btn.getContext(),
                                            "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                            .show();
                                }
                            } else if (text.contains("*")) {
                                for (int j = 0; j < text_arrayInt.length; j++) {
                                    if (Double
                                            .parseDouble(text_arrayInt[j]) < 0) {
                                        Toast.makeText(btn.getContext(),
                                                "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                                .show();
                                        result = 0.0;
                                        break;
                                    } else {
                                        if (j == 0) {
                                            result = Double
                                                    .parseDouble(text_arrayInt[j])
                                                    * Double.parseDouble(text_arrayInt[j + 1]);
                                        } else if (j < text_arrayInt.length - 1) {
                                            result = result
                                                    * Double.parseDouble(text_arrayInt[j + 1]);
                                        }
                                    }

                                }

                                if (result < 0) {
                                    result = 0.0;
                                    Toast.makeText(btn.getContext(),
                                            "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                            .show();
                                }
                            } else if (text.contains("/")
                                    && !text_arrayInt[1].equals("0")) {
                                for (int j = 0; j < text_arrayInt.length; j++) {
                                    if (Double
                                            .parseDouble(text_arrayInt[j]) < 0) {
                                        Toast.makeText(btn.getContext(),
                                                "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                                .show();
                                        result = 0.0;
                                        break;
                                    } else {
                                        if (j == 0) {
                                            result = Double
                                                    .parseDouble(text_arrayInt[j])
                                                    / Double.parseDouble(text_arrayInt[j + 1]);
                                        } else if (j < text_arrayInt.length - 1) {
                                            result = result
                                                    / Double.parseDouble(text_arrayInt[j + 1]);
                                        }
                                    }

                                }

                                if (result < 0) {
                                    result = 0.0;
                                    Toast.makeText(btn.getContext(),
                                            "请输入正确的计算数值", Toast.LENGTH_SHORT)
                                            .show();
                                }
                            }
                            DecimalFormat df = new DecimalFormat("######0.00");// 精确到小数点后的六位
                            edit_content.setText(df.format(result));
                        } else if (text.contains("日期") || text.contains("时刻")
                                || text.contains("年份")) {
                            int type = 0;
                            if (text.contains("日期")) {
                                type = 1;
                            } else if (text.contains("时刻")) {
                                type = 2;
                            } else if (text.contains("年份")) {
                                type = 3;
                            }
                            DateTimePickerView dateTimePickerView = new DateTimePickerView(
                                    activity, type);
                            dateTimePickerView.show(edit_content);
                        } else if (text.equals("获取时间")) {
                            Date date = new Date(System.currentTimeMillis());
                            SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "yyyy-MM-dd HH:mm:ss");
                            edit_content.setText(dateFormat.format(date));
                        }
                        System.out.println("点击了：" + btn.getText());
                    }
                });
            }
        } else if (field.getLabel().equals("拍照")) {

        } else {
            button_layout.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化含3和4开头的计算和日期按钮
     */
    private String initBtnLabel(BasicProperties field) {
        String input = field.getInput();
        String buttonLabel = field.getButtonlabel();
        if (input.startsWith("3") || input.contains("|3")
                || input.startsWith("4") || input.contains("|4")) {
            if (input.contains("301")) {
                buttonLabel = buttonLabel + "," + "计算中心点经度";
            }
            if (input.contains("302")) {
                buttonLabel = buttonLabel + "," + "计算中心点纬度";
            }
            if (input.contains("303")) {
                buttonLabel = buttonLabel + "," + "计算面积";
            }
            if (input.contains("304")) {
                buttonLabel = buttonLabel + "," + "计算边长";
            }
            if (input.contains("401")) {
                buttonLabel = buttonLabel + "," + "选择日期";
            }
            if (input.contains("402")) {
                buttonLabel = buttonLabel + "," + "选择时刻";
            }
            if (input.contains("403")) {
                buttonLabel = buttonLabel + "," + "选择年份";
            }
            if (input.contains("404")) {
                buttonLabel = buttonLabel + "," + "获取时间";
            }
            buttonLabel = buttonLabel.replace("null", "");
            if (buttonLabel.startsWith(",")) {
                System.out.println("截取字符：" + buttonLabel);
                buttonLabel = buttonLabel.substring(1);
            }

        }
        return buttonLabel;
    }

    String GPS = "";
    /**
     * 定位信息的广播
     *
     * @author pengling
     * @date 2015-6-29
     */
    boolean isFirst = true;

    private class GetGPSBroadcastReceiver extends BroadcastReceiver {
        private TextView edit_content;

        public GetGPSBroadcastReceiver(TextView edit_content) {
            this.edit_content = edit_content;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (!intent.getAction().equals(Constants.LOCATION_ACTION))
                return;
            if (isFirst) {
                isFirst = false;
                GPS = intent.getStringExtra(Constants.GPSFLAG);
                System.out.println("点击GPS获得的:" + GPS);
                edit_content.setText(GPS);
            }
            activity.unregisterReceiver(this);// 不需要时注销
        }
    }

    /**
     * 动态改变listview的值
     */
    class ValueWatcher implements TextWatcher {
        private TextView value;
        private String key_str;
        private String input;

        public ValueWatcher(TextView value, String key_str, String input) {
            this.value = value;
            this.key_str = key_str;
            this.input = input;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
//			System.out.println("表单框改变：" + value.getText().toString()
//					+ ((DemandMainActivity) activity).oldDataMap);
//			((DemandMainActivity) activity).isFormEdit = true;
//			((DemandMainActivity) activity).isClickSave = false;
//			String saveValue = value.getText().toString();
//			((DemandMainActivity) activity).addMap.put(key_str, saveValue);
        }
    }

    /**
     * 处理分区代码
     *
     * @param childView
     */
    public void doSetView(View childView) {
        View gray_view = (View) childView.findViewById(R.id.gray_view);
        View line_view = (View) childView.findViewById(R.id.line_view);
        if (StringUtil.isNotEmpty(field.getFieldset())) {
            if (StringUtil.isNotEmpty(fieldSet)
                    && !fieldSet.equals(field.getFieldset())) {
                gray_view.setVisibility(View.VISIBLE);
                line_view.setVisibility(View.VISIBLE);
            } else {
                gray_view.setVisibility(View.GONE);
                line_view.setVisibility(View.GONE);
            }
            fieldSet = field.getFieldset();
        }
    }

    /**
     * 解析出现“001|000”的情况
     *
     * @param childView
     */
    public static String fieldName = "";


    public static View photoView;

    public View initTakePhoto(final ImageGridAdapter imageGridAdapter) {
        View childView = (View) activity.getLayoutInflater().inflate(
                R.layout.util_form_photo, null);
        photoView = childView;
        childView.findViewById(R.id.take_photo).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (StringUtil.isFastDoubleClick(500)) {
                            return;
                        }
                        photoList = new ArrayList<String>();
                        photoKeyList = new ArrayList<String>();
                        photoMap = new HashMap<String, String>();
                        String text0 = "0";
                        if (field.getMark() != null) {

                            if (!field.getMark().isEmpty()) {
                                text = "";
                                String[] listmark = field.getMark().split(";");

                                if (listmark.length >= 1) {
                                    for (int i = 0; i < listmark.length; i++) {
                                        for (int j = 0; j < fieldList.size(); j++) {
                                            if (listmark[i].equals(fieldList
                                                    .get(j).getLabel())) {
//												text0 = ((DemandMainActivity) activity).addMap
//														.get(fieldList.get(j)
//																.getName());
                                                if (text0 == null) {
                                                    text0 = "未填";
                                                }

                                            }
                                        }
                                        String lableString = listmark[i] + ":";
                                        text = text + "," + lableString + text0;

                                        photoList.add(text0);
                                        photoKeyList.add(listmark[i]);
                                        photoMap.put(listmark[i], text0);
                                    }
                                }


                                if (text.startsWith(",")) {
                                    text = text.substring(1);
                                }


                            }
                        }
                        Constants.takePhotoFlag = "gallery";
                        Constants.new_PhotoName = null;
                        Constants.new_PhotoName = FormUtil.reName_photo();
                        System.out.println("======:" + Constants.new_PhotoName);
//						((DemandMainActivity) activity).photoUtil.takePhoto("",
//								imageGridAdapter);// ???监听得重写

                    }
                });

//		((DemandMainActivity) activity).initAdapterView(imageGridAdapter, null,
//				childView);
        Gallery gallery = (Gallery) childView.findViewById(R.id.gallery);
        imageGridAdapter.setGallery(gallery);
        gallery.setAdapter(imageGridAdapter);
        if (imageGridAdapter.imageInfoList.size() > 1) {
            gallery.setSelection(1);
        }
        return childView;
    }

    public View initTakeGirdPhoto(final ImageGridAdapter imageGridAdapter,
                                  File file) {
        System.out.println(imageGridAdapter.imageInfoList.size());
        View childView = (View) activity.getLayoutInflater().inflate(
                R.layout.util_grid_list, null);
        MyGridView gridView = (MyGridView) childView
                .findViewById(R.id.gridview);
        gridView.setPadding(0, 0, 0, 80);
        gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridView.setVerticalSpacing(10);
        gridView.setHorizontalSpacing(10);
        gridView.setAdapter(imageGridAdapter);
        if (file.getPhoto().getMaxsize().equals("1")) {
            gridView.setNumColumns(1);
        } else {
            gridView.setNumColumns(2);
        }
        gridView.setVerticalScrollBarEnabled(false);
        return childView;
    }

    /**
     * 初始化录音界面
     *
     * @param path 存放录音的地址
     * @return
     */
    public View initVoice(String path, String voiceName) {
        View childView = (View) activity.getLayoutInflater().inflate(
                R.layout.util_form_voice, null);
        TakeVoiceUtil voiceUtil = new TakeVoiceUtil(childView, activity, path,
                voiceName);
        voiceUtil.initTakeVoice();
        return childView;
    }

    /**
     * 获取输入框输入类型
     */
    public int getTextType(String input) {
        if (input.contains("000")) {
            return EditorInfo.TYPE_CLASS_TEXT;
        } else if (input.contains("001")) {
            return EditorInfo.TYPE_CLASS_PHONE;
        }
        return 00;// 不存在文本框
    }

    /**
     * 删除多余的数据
     *
     * @param oldDataMap
     * @param addMap
     * @param surveyPath
     * @param photoKey
     */
    public static void deleteNoData(Map<String, String> oldDataMap,
                                    Map<String, String> addMap, String surveyPath, String photoKey) {
        // 删除多余的照片
        if (oldDataMap.isEmpty()
                || StringUtil.isEmpty(oldDataMap.get(photoKey))
                && !addMap.isEmpty()) {//
            if (StringUtil.isNotEmpty(addMap.get(photoKey))) {
                String newPaths[] = addMap.get(photoKey).split(",");
                for (String string : newPaths) {
                    FileUtil.deleteFile(surveyPath + string);
                    System.out.println("000deleteFile" + surveyPath);

                }
            }
        } else if (!oldDataMap.isEmpty() && !addMap.isEmpty()
                && !StringUtil.isEmpty(oldDataMap.get(photoKey))
                && !StringUtil.isEmpty(addMap.get(photoKey))) {
            String newPaths[] = addMap.get(photoKey).split(",");
            String oldPaths = oldDataMap.get(photoKey);
            for (String string : newPaths) {// 删除多拍的照片
                // for (String old : oldPaths) {
                // if (!old.equals(string)) {
                // photoUtil.deleteAttachmentFile(surveyPath
                // + string);
                // System.out.println("111deleteFile"+surveyPath);
                // break;
                // }
                // }
                if (!oldPaths.contains(string)) {
                    FileUtil.deleteFile(surveyPath + string);
                    System.out.println("111deleteFile" + surveyPath + string);
                }
            }
        }
    }

    public static String reName_photo() {
        // if (StringUtil.isFastDoubleClick(500)) {
        // System.out.println("=================");
        // return null;
        //
        // }
        String text0 = "0";
        if (field.getStr_NamePhoto() != null) {

            if (!field.getStr_NamePhoto().isEmpty()) {
                text_pho = "";
                String[] listpn = field.getStr_NamePhoto().split(";");

                if (listpn.length >= 1) {
                    for (int i = 0; i < listpn.length; i++) {
                        for (int j = 0; j < fieldList.size(); j++) {
                            if (listpn[i].equals(fieldList.get(j).getLabel())) {
//								text0 = ((DemandMainActivity) activity).addMap
//										.get(fieldList.get(j).getName());
                                if (text0 == null) {
                                    text0 = "";
                                }

                            }
                        }
                        text_pho = text_pho + "_" + text0;
                    }
                }
                if (text_pho.startsWith("_")) {
                    text_pho = text_pho.substring(1);
                }
            }
        }
        System.out.println("======:" + text_pho);
        return text_pho;
    }


    //=====================================================================

    /**
     * 普通单行输入框
     */
    public View initNormalEditText(int inputType, int imeOptions, String title,
                                   Map<String, String> dataMap) {
        View childView = (View) activity.getLayoutInflater().inflate(R.layout.util_form_edittext, null);
        TextView title_text = (TextView) childView.findViewById(R.id.title_text);
        if (StringUtil.isEmpty(title)) {
            title = field.getLabel();
        }
        title_text.setText(title);
        doSetView(childView);
        final ClearEditText edit_content = (ClearEditText) childView.findViewById(R.id.edit_content);
        edit_content.setInputType(inputType);
        if (inputType == 00) {// 非00
            edit_content.setFocusable(false);
            edit_content.setEnabled(false);
        }
        if (dataMap != null) {// 获得老值
            String value = dataMap.get(field.getName());
            edit_content.setText(value);
            if (StringUtil.isNotEmpty(value)) {
                edit_content.setSelection(value.length());
            }
            if (field.isShow() && !field.isEditable()) {// 显示但不可编辑
                edit_content.setEnabled(false);
                edit_content.setFocusable(false);
            }
        }

        initButtonView(childView, edit_content);// 增加小按钮

        edit_content.addTextChangedListener(new InputValueWatcher(edit_content, field.getName(), field.getInput()));
        return childView;
    }

    /**
     * 普通文本域
     */
    public View initTextArea(String title, Map<String, String> dataMap) {

        View childView = (View) activity.getLayoutInflater().inflate(R.layout.util_form_textarea, null);
        TextView title_text = (TextView) childView.findViewById(R.id.title_text);
        if (StringUtil.isEmpty(title)) {
            title = field.getLabel();
        }
        title_text.setText(title);
        doSetView(childView);
        final ClearEditText edit_content = (ClearEditText) childView.findViewById(R.id.edit_content);

        edit_content.setSingleLine(false);


        if (dataMap != null) {// 获得老值
            String value = dataMap.get(field.getName());
            edit_content.setText(value);
            if (StringUtil.isNotEmpty(value)) {
                edit_content.setSelection(value.length());
            }
            if (field.isShow() && !field.isEditable()) {// 显示但不可编辑
                edit_content.setEnabled(false);
                edit_content.setFocusable(false);
            }
        }
        edit_content.addTextChangedListener(new InputValueWatcher(edit_content, field.getName(), field.getInput()));
        return childView;
    }

    /**
     * 初始化选框输入框
     */
    public View initSelectInput(String title, Map<String, String> dataMap, final List<KeyValueBean> list,
                                boolean isSingle, String beanType) {
        //渲染
        View childView = (View) activity.getLayoutInflater().inflate(R.layout.util_form_select, null);
        final TextView text_id = (TextView) childView.findViewById(R.id.text_id);
        final EditText edit_content = (EditText) childView.findViewById(R.id.edit_content);
        final TextView text_content = (TextView) childView.findViewById(R.id.text_content);
        TextView title_text = (TextView) childView.findViewById(R.id.title_text);

        //标题
        if (StringUtil.isNotEmpty(title)) {
            title_text.setText(title);
        } else {
            title_text.setText(field.getLabel());
        }
        int textType = getTextType(field.getInput());
        if (textType != 00) {// 可编辑
            edit_content.setVisibility(View.VISIBLE);
            text_content.setVisibility(View.GONE);
            edit_content.setInputType(textType);
            edit_content.setEnabled(true);
            edit_content.setFocusableInTouchMode(true);
            edit_content.setFocusable(true);
            edit_content.requestFocus();
            initSelectList(edit_content, text_id, dataMap, list, isSingle, true, beanType);
        } else {
            edit_content.setVisibility(View.GONE);
            text_content.setVisibility(View.VISIBLE);
            text_content.setFocusableInTouchMode(true);
            text_content.setFocusable(true);
            text_content.requestFocus();
            text_content.setEnabled(true);
            initSelectList(edit_content, text_id, dataMap, list, isSingle, false, beanType);
        }
        return childView;
    }

    /**
     * 初始化选择输入框的选择列表
     */
    private void initSelectList(final TextView edit_content, final TextView text_id,
                                Map<String, String> dataMap, final List<KeyValueBean> list,
                                final boolean isSingle, final boolean isEdit, final String beanType) {
        if (dataMap != null) {
            String value = dataMap.get(field.getName());
            String newValue = "", newId = "";
            if (list != null && list.size() > 0 && StringUtil.isNotEmpty(value)) {
                for (KeyValueBean keyValueBean : list) {
                    String key = keyValueBean.getKey();
                    String selectValue = keyValueBean.getValue();
                    if (value.contains(",")) {// 多个
                        String val[] = value.split(",");// value=112,333
                        for (String str : val) {// str=112
                            if (key.equals(str)) {
                                if (StringUtil.isEmpty(newValue)) {
                                    newValue = selectValue;
                                } else {
                                    newValue = newValue + "," + selectValue;
                                }

                                if (StringUtil.isNotEmpty(selectValue)
                                        && str.contains(selectValue)) {// str=春小麦(117)
                                    // selectValue=春小麦
                                    if (StringUtil.isEmpty(newId)) {
                                        newId = key;
                                    } else {
                                        newId = newId + "," + key;
                                    }
                                }
                            }
                        }
                    } else {//只有一个
                        if (key.equals(value)) {
                            newValue = selectValue;
                        }
                        if (value.contains(selectValue)) {// str=春小麦(117)
                            if (StringUtil.isEmpty(newId)) {
                                newId = key;
                            }
                        }
                    }
                }//list循环结束
            }


            if (StringUtil.isEmpty(newValue)) {
                newValue = value;
            }
            if (StringUtil.isEmpty(newId)) {
                newId = value;
            }
            System.out.println("newId:" + newId);
            edit_content.setText(newValue);
            text_id.setText(newId);
            if (field.isShow() && !field.isEditable()) {// 显示但不可编辑
                edit_content.setEnabled(false);
                edit_content.setFocusable(false);
            }
        }

        edit_content.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    boolean touchable = event.getX() > (edit_content.getWidth() - edit_content
                            .getTotalPaddingRight())
                            && (event.getX() < ((edit_content.getWidth() - edit_content
                            .getPaddingRight())));

                    if (touchable || !isEdit) {
                        System.out.println("点击添加了");
                        // 判断隐藏软键盘是否弹出
                        if (activity.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                            // 隐藏软键盘
                            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                        }
                        MyActorPopWindow myActorWindow = new MyActorPopWindow(
                                activity, v, isSingle);
                        myActorWindow.showActorPanel(text_id, edit_content,
                                list, beanType);

                        // 判断隐藏软键盘是否弹出
                        if (activity.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                            // 隐藏软键盘
                            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                        }
                    }
                }
                return false;
            }
        });
        edit_content.addTextChangedListener(new InputValueWatcher(edit_content,
                field.getName(), field.getInput()));
    }


    /**
     * 动态改变listview的值
     */
    class InputValueWatcher implements TextWatcher {
        private TextView value;
        private String key_str;
        private String input;

        public InputValueWatcher(TextView value, String key_str, String input) {
            this.value = value;
            this.key_str = key_str;
            this.input = input;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable arg0) {
//            ((MyDemandActivity) activity).isFormEdit = true;
//            ((MyDemandActivity) activity).isClickSave = false;
//            String saveValue = value.getText().toString().trim();
//            ((MyDemandActivity) activity).addMap.put(key_str, saveValue);
        }
    }
}
